﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgNetComponentsDx.Language;
using System.IO;
using System.Data.SqlServerCe;
using ProgNetComponents.Data.SqlCe;
using ProgNetComponentsDx.Browsers;

namespace SqlCeManager.Tools
{
    public partial class ConnectionForm : XtraForm
    {
        private int _Id;
        public int Id
        {
            get { return _Id; }
        }

        public ConnectionForm()
        {
            InitializeComponent();
        }
        
        string _ConnectionString;
        public string ConnectionString { get { return _ConnectionString; } }

        public string FileName
        {
            get
            {
                string file = fileDialogEdit1.EditValue.AsString();
                if (!file.ToLower().EndsWith(".sdf"))
                    file += ".sdf";
                return file;
            }
        }

        private bool ValidateAll()
        {
            dxErrorProvider1.ClearErrors();
            if (modeProvider1.CurrentMode == ProgNetComponentsDx.Enums.FormMode.New)
            {
                if (tePass.EditValue.IsNotNull())
                {
                    if (tePass.EditValue.AsString() != tePass2.EditValue.AsString())
                    {
                        dxErrorProvider1.SetError(tePass2, ProgNetLanguage.sGetString("ERR_PAS_MATCH"));
                        return false;
                    }
                    if (tePass.EditValue.AsString().XMatch("[^a-zA-Z0-9]"))
                    {
                        dxErrorProvider1.SetError(tePass2, ProgNetLanguage.sGetString("ERR_PAS_INVALID_CHAR"));
                        return false;
                    }
                }
            }
            return true;
        }

        public bool Connect()
        {
            bool result = true;
            if (!ValidateAll())
            {
                return false;
            }
            bool isNew = modeProvider1.CurrentMode == ProgNetComponentsDx.Enums.FormMode.New;
            _ConnectionString = getConnectionString();

            if (isNew)
            {
                try
                {
                    SqlCeEngine engine = new SqlCeEngine(ConnectionString);
                    engine.CreateDatabase();
                }
                catch (Exception ex)
                {
                    this.ShowDxLngErrorDialog("ERROR_CREATE_DB", Application.ProductName, ex.Message);
                    result = false;
                }
            }
            if (result)
            {
                SqlCeConnection conn = null;
                try
                {
                    conn = new SqlCeConnection(ConnectionString);
                    conn.Open();
                }
                catch (Exception ex)
                {
                    this.ShowDxLngErrorDialog("ERROR_CONNECTING_TO_DB", ex.Message);
                    result = false;
                }
                finally
                {
                    if (conn != null)
                        try { conn.Close(); }
                        catch { }
                }
            }
            return result;
        }

        private string getConnectionString()
        {
            string str = "Data Source=" + FileName +  ";";
            if (tePass.EditValue.IsNotNull())
                str += "Encrypt Database=True;Password=" + tePass.EditValue.AsString() + ";";
            else
                str += "Encrypt Database=False;";
            str += "Max Database Size = 4091";
            return str;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (Connect())
            {
                DataRow r = browserProvider1.GetSettings(fileDialogEdit1).AdditionalBrowser.GetTable().SelectFirstRow("STP_POL_PLIK = " + FileName.EscapeSql());
                if (r == null)
                {
                    SqlCeDataManager  manager = new SqlCeDataManager();

                    Setup.PolaczeniaDataSet ds = new Setup.PolaczeniaDataSet();
                    manager.AddTableDef(ds.STP_POLACZENIA);

                    ds.STP_POLACZENIA.AddSTP_POLACZENIARow(Path.GetFileNameWithoutExtension(FileName),
                        FileName,
                        tePass.EditValue.AsString(), getConnectionString());
                    manager.UpdateDataSet(ds);
                    BrowserCache.RefreshCache(ds);
                    _Id = ds.STP_POLACZENIA[0].STP_POL_ID;
                }
                else
                {
                    _Id = r["STP_POL_ID"].AsInt(-1);
                }
                DialogResult = DialogResult.OK;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void fileDialogEdit1_EditValueChanged(object sender, EventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            if (fileDialogEdit1.EditValue.IsNotNull())
            {
                btnOK.Enabled = true;
                try
                {
                    if (!File.Exists(fileDialogEdit1.EditValue.AsString()))
                        modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.New;
                    else
                        modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.Edit;
                }
                catch
                {
                    dxErrorProvider1.SetError(fileDialogEdit1, ProgNetLanguage.sGetString("FILE_ERROR"));
                }
            }
            else
            {
                btnOK.Enabled = false;
            }
        }

        private void BrowserSettings_AdditionalBrowserValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            e.Cancel = true;
            if (e.NewValue.IsNotNull())
            {
                DataRow r = browserProvider1.GetSettings(sender).AdditionalBrowser.GetRowForValue(e.NewValue);
                if (r != null)
                {
                    (sender as BaseEdit).EditValue = r["STP_POL_PLIK"].ToString();
                }
            }
        }
    }
}
